//
//  DDEAddProblemViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-7-4.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "DDEAddProblemViewController.h"
#import "CameraAlbum.h"
#import "MTStatusBarOverlay.h"
#import "PhotoTableViewCell.h"


@interface DDEAddProblemViewController () <UIActionSheetDelegate,UITableViewDataSource,UITableViewDelegate,
    CameraAlbumDelegate,PhotoTableCellDelegate>

@property (weak, nonatomic) IBOutlet UITextView *contentTv;
@property (weak, nonatomic) IBOutlet UIButton *addPictureBtn;
@property (weak, nonatomic) IBOutlet UITableView *pictureTable;

@property (nonatomic, strong) CameraAlbum *cameraAlbum;
@property (nonatomic, strong) NSMutableArray *imageList;

- (IBAction)takePhotoAction:(id)sender;
- (IBAction)finishSubmitIssueAction:(id)sender;


@end

@implementation DDEAddProblemViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIToolbar * topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
    [topView setBarStyle:UIBarStyleDefault];
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(320-42, 3, 40, 26);
    [button setTitle:@"完成" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [button addTarget:self action:@selector(dismissKeyBoard:) forControlEvents:UIControlEventTouchUpInside];
    
    [topView addSubview:button];
    
    [self.contentTv setInputAccessoryView:topView];
    
    [self initHUD];
    
    self.imageList = [NSMutableArray array];
    
    [self transAppTableToHorizontal];
}

- (void)transAppTableToHorizontal {
    CGRect frame = self.pictureTable.frame;
    
    self.pictureTable.showsVerticalScrollIndicator = NO;
    self.pictureTable.showsHorizontalScrollIndicator = NO;
    self.pictureTable.transform = CGAffineTransformMakeRotation(-M_PI * 0.5);
    self.pictureTable.frame = frame;
    self.pictureTable.clipsToBounds = NO;
    self.pictureTable.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.pictureTable.separatorColor = [UIColor clearColor];
    self.pictureTable.dataSource = self;
    self.pictureTable.delegate = self;
    self.pictureTable.pagingEnabled = YES;
    
}

- (void)dismissKeyBoard:(id)sender {
    [self.contentTv resignFirstResponder];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    self.title = @"新增问题";
    
    [self updateViewWithData];
    
    self.showLeftBtn = YES;
    self.showRightBtn = YES;
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
    
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_n.png"] forState:UIControlStateNormal];
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_p.png"] forState:UIControlStateHighlighted];
    [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_确认_n.png"] forState:UIControlStateNormal];
    [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_确认_p.png"] forState:UIControlStateHighlighted];
    
}

- (void)updateViewWithData {
    NSDictionary *info = self.problemInfo;
    if ([info count] > 0) {
        NSString *name = [info objectForKey:@"xmmc"];
        if ([name length] > 0) {
            self.title = name;
        } else {
            self.title = @"新增问题";
        }
    }
}

- (void)leftNavItemAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightNavItemAction:(id)sender {
    if ([self.contentTv hasText]) {
        
        BOOL needPhoto = [[self.problemInfo objectForKeyOrNil:@"sfpz"] boolValue]; //是否需要拍照
        if (needPhoto && [self.imageList count] == 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:@"该项目必须要照片，请上传照片后提交"
                                                           delegate:nil
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
            [alert show];
            
        } else if (needPhoto && [self.imageList count] >11 ) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:@"照片超过11张，请确认后提交"
                                                           delegate:nil
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
            [alert show];
            
        } else {
            
            [self.HUD show:YES];
            
            [self performSelectorInBackground:@selector(submitIssueReuqest) withObject:nil];
        }

    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"问题描述不能为空，请填写之后再提交"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

- (void)submitIssueReuqest {
    NSMutableArray *fileList = [NSMutableArray array];
    if ([self.imageList count] > 0) {
        
        for (int i = 0; i < [self.imageList count]; i ++) {
            UIImage *image = (UIImage *)[self.imageList objectAtIndex:i];
            NSData *imgData = nil;
            NSString *imagetype = @".jpeg";
            if (image != nil) {
                if (UIImagePNGRepresentation(image) == nil) {
                    imgData = UIImageJPEGRepresentation(image, 1);
                    imagetype = @".jpeg";
                } else {
                    imgData = UIImagePNGRepresentation(image);
                    imagetype = @".png";
                }
            }
            
            NSString *fileName = [NSString stringWithFormat:@"%d%@",i+1,imagetype];
            NSDictionary *fileDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                      imgData,@"path",
                                      fileName,@"name", nil];
            [fileList addObject:fileDict];
        }
    }
    
    NSString *projectID = [self.problemInfo objectForKey:@"id"];
    NSString *wtms = self.contentTv.text; //问题描述
    
    NSDate *date = [NSDate date];
    NSTimeInterval timeInterval = [date timeIntervalSince1970];
    long interval = (long)timeInterval;
    
    NSDictionary *info = self.problemInfo;
    NSDictionary *erandInfo = self.erandInfo;
    NSString *ldpc = [NSString stringWithFormat:@"%@",[info objectForKeyOrNil:@"ldpc"]];
    NSString *pc = [NSString stringWithFormat:@"%@",[erandInfo objectForKeyOrNil:@"pc"]];
    UserInfo *user = [UserInfo instance];
    NSString *gonghao = [user.info objectForKeyOrNil:@"gh"];
    NSString *wtpc = [NSString stringWithFormat:@"%ld",interval];
    NSString *path = [NSString stringWithFormat:@"app/%@/%@/%@/%@/",gonghao,pc,ldpc,wtpc];
    //        NSLog(@"*******path:%@",path);
    
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           fileList,@"FILE",
                           projectID,@"id",
                           wtms,@"wtms",
                           wtpc,@"wtpc",
                           path,@"md_input_path", nil];
    [self.networkManager requestWithMethod:issueSubmit parameter:param delegate:self];
}

//点击拍照按钮
- (IBAction)takePhotoAction:(id)sender {
//    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
//                                                             delegate:self
//                                                    cancelButtonTitle:@"取消"
//                                               destructiveButtonTitle:nil
//                                                    otherButtonTitles:@"拍照",@"从相册选择", nil];
//    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
//    [actionSheet showInView:self.view];
    
    [self openSystemCamera];
}

- (IBAction)finishSubmitIssueAction:(id)sender {
    NSDictionary *info = self.problemInfo;
    NSDictionary *erandInfo = self.erandInfo;
    NSString *ldid = [NSString stringWithFormat:@"%@",[info objectForKeyOrNil:@"id"]];
    NSString *ldpc = [NSString stringWithFormat:@"%@",[info objectForKeyOrNil:@"ldpc"]];
    NSString *pc = [NSString stringWithFormat:@"%@",[erandInfo objectForKeyOrNil:@"pc"]];
    UserInfo *user = [UserInfo instance];
    NSString *gonghao = [user.info objectForKeyOrNil:@"gh"];
    
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           ldid,@"id",
                           ldpc,@"ldpc",
                           pc,@"pc",
                           gonghao,@"gh", nil];
    [self.networkManager requestWithMethod:projectSubmit parameter:param delegate:self];
    [self.HUD show:YES];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        [self openSystemCamera];
    }
    else if (buttonIndex==1) {
        [self openSystemImageLib];
    }
}

#pragma mark - Camera
- (void)openSystemCamera{
    if (self.cameraAlbum==nil) {
        self.cameraAlbum = [CameraAlbum instance];
        self.cameraAlbum.delegate = self;
    }
    [self.cameraAlbum openCameraInTargetViewController:self];
}

- (void)openSystemImageLib{
    if (self.cameraAlbum==nil) {
        self.cameraAlbum = [CameraAlbum instance];
        self.cameraAlbum.delegate = self;
    }
    [self.cameraAlbum openPhotoLibraryInTargetViewController:self];
}

#pragma mark - CameraAlbumDelegate
//压缩图片
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this newcontext, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}

- (UIImage *)setTheSeletedImage:(UIImage *)image
{//压缩图片
    UIImage *returnImage = [[UIImage alloc]init];
    //h=720, w=640
    if (image.size.height > image.size.width) {
        if (image.size.height < 640) {
            returnImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(image.size.width, image.size.height)];
        }else{
            returnImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(image.size.width*640/image.size.height, 640)];
        }
        
    } else {
        if (image.size.width < 640) {
            returnImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(image.size.width, image.size.height)];
        }else {
            returnImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(640, image.size.height*640/image.size.width)];
        }
    }
    return returnImage;
    //压缩后图片
}

-(void)getSavedImage:(UIImage*)image {
    UIImage *selectedImage = [self setTheSeletedImage:image];
    if (self.imageList == nil) {
        self.imageList = [NSMutableArray array];
    }
    if (selectedImage != nil) {
        [self.imageList addObject:selectedImage];
    }
    [self.pictureTable reloadData];
}

- (void)didFinishedPickImageWithURL:(NSString *)url {
    NSLog(@"*****image url:%@",url);
    
//    if ([self.contentTv hasText]) {
//        NSString *projectID = [self.problemInfo objectForKey:@"id"];
//        NSString *wtms = self.contentTv.text; //问题描述
//        
//        NSDictionary *fileDict = [NSDictionary dictionaryWithObjectsAndKeys:url,@"path", nil];
//        
//        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
//                               fileDict,@"FILE",
//                               projectID,@"id",
//                               wtms,@"wtms", nil];
//        [self.networkManager requestWithMethod:issueSubmit parameter:param delegate:self];
//        [self.HUD show:YES];
//    }
    
}

- (void)clearViewContent {
    self.contentTv.text = @"";
    
    [self.imageList removeAllObjects];
    [self.pictureTable reloadData];
}

#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    
    if (methodId == issueSubmit) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) { //请求成功
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        NSInteger resultCode = [[dataObject objectForKeyOrNil:@"result"] integerValue];
                        NSString *msg = @"";
                        if (resultCode == 0) {
                            
                            msg = @"问题已经提交成功，可以继续添加问题";
                            
                            [self showAlertViewWithMessage:msg];
                            
                            [self performSelector:@selector(clearViewContent) withObject:nil afterDelay:0.9];
                            
                            
                        } else {
                            
                            msg = @"问题提交失败";
                            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                            message:msg
                                                                           delegate:nil
                                                                  cancelButtonTitle:@"确定"
                                                                  otherButtonTitles:nil];
                            [alert show];
                        }
                        
                    }
                }
            }
        }
    } else if (methodId == projectSubmit) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) { //请求成功
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        NSInteger resultCode = [[dataObject objectForKeyOrNil:@"result"] integerValue];
                        NSString *msg = @"";
                        if (resultCode == 2) {
                            msg = @"临店问题提交成功！";
                            
                            [self showAlertViewWithMessage:msg];
                            
                            [self performSelector:@selector(leftNavItemAction:) withObject:nil afterDelay:0.9];
                        } else {
                            if (resultCode == 0) {
                                msg = @"系统错误，问题提交失败";
                            } else if (resultCode == 1) {
                                msg = @"还没有问题提交，请先提交问题";
                            }
                            
                            [self showAlertViewWithMessage:msg];
                        }
                    }
                }
            }
        }
    }
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    
    [self.HUD hide:YES];
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    if ([msg isKindOfClass:[NSNull class]] || [msg length] == 0) {
        msg = @"请求失败，请稍后重试";
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                    message:msg
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.imageList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"identifier";
    PhotoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[PhotoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        [cell setBackgroundColor:[UIColor clearColor]];
        cell.delegate = self;
    }
    
    int row = indexPath.row;
    if ([self.imageList count] > row) {
        UIImage *image = [self.imageList objectAtIndex:row];
        [cell updateDatas:image atIndex:indexPath];
    }
    
    return cell;
    
}

#pragma mark - UITableViewDelegate methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 70.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - PhotoTableViewCellDelegate
- (void)willDeleteItem:(PhotoItemView *)item inCell:(PhotoTableViewCell *)cell {
    NSIndexPath *indexPath = cell.indexPath;
    NSInteger row = indexPath.row;
    if (0 <= row && [self.imageList count] > row) {
        [self.imageList removeObjectAtIndex:row];
    }
    [self.pictureTable reloadData];
}

@end
